import 'package:flutter/material.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

import '../utils/logger.dart';

class SelectItem {
  final String key;
  final String label;
  final bool disabled;
  final Widget? icon;

  SelectItem({
    required this.key,
    required this.label,
    this.icon,
    this.disabled = false,
  });

  @override
  operator ==(Object? other) {
    if (other is! SelectItem) return false;
    return key == other.key;
  }

  @override
  int get hashCode => key.hashCode;
}

class SelectWidget extends StatefulWidget {
  final String value;
  final List<SelectItem> lists;
  final void Function(SelectItem)? onChanged;

  final BoxShape? shape;
  final BorderRadius? borderRadius;
  final Color? backgroundColor;
  final double elevation;

  const SelectWidget({
    Key? key,
    this.value = '',
    required this.lists,
    this.onChanged,
    this.shape,
    this.borderRadius,
    this.backgroundColor,
    this.elevation = 0.0,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => _SelectWidgetState();
}

class _SelectWidgetState extends State<SelectWidget> {
  late SelectItem item;

  @override
  void initState() {
    super.initState();
    if (widget.lists.isEmpty) {
      item = SelectItem(key: '', label: '暂无选项');
    } else if (widget.value.isEmpty) {
      item = widget.lists.first;
    } else {
      item = widget.lists.firstWhere((element) => element.key == widget.value,
          orElse: () => widget.lists.first);
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _showSelector,
      child: PhysicalModel(
        elevation: widget.elevation,
        shape: widget.shape ?? BoxShape.rectangle,
        color: widget.backgroundColor ?? Colors.black12,
        borderRadius: widget.borderRadius ?? BorderRadius.circular(30),
        child: Container(
          color: Colors.transparent, // 增加事件响应范围
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                if (item.icon != null) item.icon!,
                Text(item.label),
                const Spacer(),
                const Icon(Icons.arrow_drop_down),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showSelector() async {
    if (widget.lists.isEmpty) return;

    final selectItem = await MyDialog.of(context).popup<SelectItem?>(
        SelectPopupPanel(
            lists: widget.lists, selectedIndex: widget.lists.indexOf(item)));
    if (selectItem != null) {
      setState(() {
        item = selectItem;
      });
      widget.onChanged?.call(item);
    }
  }
}

class SelectPopupPanel extends StatefulWidget {
  final List<SelectItem> lists;
  final int selectedIndex;

  const SelectPopupPanel(
      {Key? key, required this.lists, this.selectedIndex = 0})
      : super(key: key);

  @override
  State<SelectPopupPanel> createState() => _SelectPopupPanelState();
}

class _SelectPopupPanelState extends State<SelectPopupPanel> {
  int selectedIndex = 0;
  late FixedExtentScrollController _controller;

  @override
  void initState() {
    super.initState();
    selectedIndex = widget.selectedIndex;
    _controller = FixedExtentScrollController(initialItem: selectedIndex);
  }

  Widget _buildItem(SelectItem item, [Widget? suffix]) {
    return GestureDetector(
      onTap: () {
        logger.info(item);
        selectedIndex = widget.lists.indexOf(item);
        _controller.animateToItem(selectedIndex,
            duration: const Duration(milliseconds: 300),
            curve: Curves.bounceOut);
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.black12,
          borderRadius: BorderRadius.circular(5),
        ),
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Spacer(),
            if (item.icon != null) item.icon!,
            Text(item.label),
            const Spacer(),
            if (suffix != null) suffix,
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            TextButton(
              onPressed: () {
                Navigator.pop(context, null);
              },
              child: const Text('取消'),
            ),
            const Spacer(),
            TextButton(
              onPressed: () {
                Navigator.pop(context, widget.lists[selectedIndex]);
              },
              child: const Text('确定'),
            ),
          ],
        ),
      ),
      Expanded(
        child: ListWheelScrollView.useDelegate(
          controller: _controller,
          physics: const FixedExtentScrollPhysics(),
          itemExtent: 40,
          squeeze: 0.8,
          childDelegate: ListWheelChildBuilderDelegate(
            childCount: widget.lists.length,
            builder: (BuildContext context, int index) {
              return _buildItem(widget.lists[index]);
            },
          ),
          onSelectedItemChanged: (index) {
            selectedIndex = index;
          },
        ),
      )
    ]);
  }
}
